package com.adlotto2.android.common;

import java.util.ArrayList;

import org.w3c.dom.Element;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.adlotto2.android.R;
import com.adlotto2.android.cronos.data.CNLottoAdLottoData;
import com.adlotto2.android.cronos.datahandler.CNBaseDataParser;
import com.adlotto2.android.cronos.datahandler.CNBaseDataSet;
import com.adlotto2.android.cronos.datahandler.CNResultSet;
import com.adlotto2.android.cronos.http.CNLottoAdApiSetEx;
import com.adlotto2.android.cronos.parser.CNLottoParser;
import com.adlotto2.android.util.ApplicationUtils;
import com.adlotto2.android.util.CNCronosLog;
import com.adlotto2.android.util.LottoAdImageDownloaderFile;

/**
 * 로또 보기 Activity
 * @author Administrator
 *
 */
public class LottoAdFullActivity extends BaseActivity {

	private MediaPlayer mMediaPlayer;
	private LottoAdImageDownloaderFile mImageDownloader;
	private ProgressBar mProgressBar;

	private int mCurrentIndex = -1;

	private final int INDEX_LOTTO_REQUEST = 0;
	private final int INDEX_LOTTO_SAVE = 1;

	private static Handler mHandler;
	private Context mContext;

	private Intent mIntent;
	private String mSendSeq;
	
	private int mLottoCount = 0;
	
	/*
	 * 5초동안 이미지를 보는 사이에 다음광고를 미리 다운로드 받기 위한 인덱스
	 */
	private int mDownloadImageIndex = 0;
	
	private boolean mWorkingThread = false;

	private ImageView mAdImage;
	private RelativeLayout mNumLayout;

	private Button mNum1Btn;
	private Button mNum2Btn;
	private Button mNum3Btn;
	private Button mNum4Btn;
	private Button mNum5Btn;
	private Button mNum6Btn;
	private Button mNumSaveBtn;
	
	private Button[] mNumBtnArr;

	private TextView mCommentTv;

	private final static int NUM_DELAY_TIME =  5000;

	private ArrayList<String> mBgArr;
	private ArrayList<String> mNumArr;

	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_full_ad;
	}

	@Override
	protected void onInit() {
		buildComponent();
	}

	private void buildComponent() {
		this.mContext = this;
		//mImageDownloader = new LottoAdImageDownloader(mContext);
		mImageDownloader = new LottoAdImageDownloaderFile(mContext);
		mProgressBar = (ProgressBar) findViewById(R.id.ProgressBarLayout);

		mBgArr = new ArrayList<String>();
		mNumArr = new ArrayList<String>();

		mIntent = getIntent();

		Bundle bundle = mIntent.getExtras();

		if (bundle != null) {
			mSendSeq = mIntent.getStringExtra("sendSeq");
		}

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

		mHandler = new Handler();

		mNumLayout = (RelativeLayout) findViewById(R.id.layout_lotto_num);
		mCommentTv = (TextView) findViewById(R.id.textview_comment);

		mAdImage = (ImageView) findViewById(R.id.imageview_fullad);

		mNum1Btn = (Button) findViewById(R.id.button_num1);
		mNum2Btn = (Button) findViewById(R.id.button_num2);
		mNum3Btn = (Button) findViewById(R.id.button_num3);
		mNum4Btn = (Button) findViewById(R.id.button_num4);
		mNum5Btn = (Button) findViewById(R.id.button_num5);
		mNum6Btn = (Button) findViewById(R.id.button_num6);
		mNumSaveBtn = (Button) findViewById(R.id.button_num_save);

		mNumBtnArr = new Button[]{mNum1Btn, mNum2Btn, mNum3Btn, mNum4Btn, mNum5Btn, mNum6Btn};
		
		mNum1Btn.setOnClickListener(mImageClickListener);
		mNum2Btn.setOnClickListener(mImageClickListener);
		mNum3Btn.setOnClickListener(mImageClickListener);
		mNum4Btn.setOnClickListener(mImageClickListener);
		mNum5Btn.setOnClickListener(mImageClickListener);
		mNum6Btn.setOnClickListener(mImageClickListener);
		mAdImage.setOnClickListener(mImageClickListener);
		mNumSaveBtn.setOnClickListener(mImageClickListener);

		mMediaPlayer = MediaPlayer.create(mContext, R.raw.bgm1);
		mMediaPlayer.setLooping(true);

		mCurrentIndex = INDEX_LOTTO_REQUEST;
		setButtonClickable(false);
	}
	
	private void setSaveClickListener(){
		mNumSaveBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mCurrentIndex = INDEX_LOTTO_SAVE;
				onRequestData();
			}
		});
	}
	
	private View.OnClickListener mImageClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {

			setButtonClickable(false);
			
			CNCronosLog.d("mLottoCount===============>" + mLottoCount);
			recycleBitmap(mAdImage);
			mWorkingThread = false;
			if(mImageDownloader.download(mBgArr.get(mLottoCount + 1), mAdImage, mProgressBar) == true) {
				imageDownloaded();
			}
			
			mNumLayout.setVisibility(View.GONE);
			
			if(mLottoCount == 0) {
				// "행운을 기원!" 메시지를 초기화 한다.
				initLottoButtonText(false);
			}
			
			if(mLottoCount < 6){
				setBackGroundNum(mNumBtnArr[mLottoCount], mNumArr.get(mLottoCount));
				mNumBtnArr[mLottoCount].setText(String.valueOf(mNumArr.get(mLottoCount)));
				visibleButton(mNumBtnArr[mLottoCount]);
				mLottoCount++;
			} else if(mLottoCount == 6) {
				mLottoCount++;
			}
		}
	};

	/*
	 * 버튼을 visible 처리한다. 
	 * @param	[IN] button: visible처리 할 버튼
	 * @return	-
	 */
	private void visibleButton(Button button) {
		button.setVisibility(View.VISIBLE);
	}
	
	/*
	 * 로또 버튼에 대한 메시지를 초기화 한다.
	 * @param	[IN] bClear: 초기화 여부(false: text를 모두 지움, true: 기본 메시지로 설정)
	 * @return	-
	 */
	private void initLottoButtonText(boolean bClear) {
		if(bClear == false) {
			mNum1Btn.setText("");
			mNum2Btn.setText("");
			mNum3Btn.setText("");
			mNum4Btn.setText("");
			mNum5Btn.setText("");
			mNum6Btn.setText("");
		} else {
			mNum1Btn.setText("행");
			mNum2Btn.setText("운");
			mNum3Btn.setText("을");
			mNum4Btn.setText("기");
			mNum5Btn.setText("원");
			mNum6Btn.setText("!");
		}
	}

	/*
	 * 광고를 본 후, 일정 시간(5초설정) 뒤에 시작되는 스레드로 로또 번호를 보여준다.
	 */
	private class setEnabledRunnable implements Runnable {

		@Override
		public void run() {
			CNCronosLog.d("========setEnabledRunnable Start========");

			// 로또 버튼
			if(mLottoCount == 0){
				// 로또 버튼에 대한 텍스트 초기화
				initLottoButtonText(true);
			} else if(mLottoCount == 7) {
				// 로또 버튼 숨김
				mNum1Btn.setVisibility(View.GONE);
				mNum2Btn.setVisibility(View.GONE);
				mNum3Btn.setVisibility(View.GONE);
				mNum4Btn.setVisibility(View.GONE);
				mNum5Btn.setVisibility(View.GONE);
				mNum6Btn.setVisibility(View.GONE);
			}
			
			// 저장 버튼에 대한 메시지 설정
			if(mLottoCount < 6) {
				mNumSaveBtn.setText("콕");
			} else if(mLottoCount == 6) {
				mNumSaveBtn.setText("저장");
			} else if(mLottoCount == 7) {
				mNumSaveBtn.setText("확인");
			}
			
			// textview_comment에 대한 설정
			if(mLottoCount == 7) {
				mCommentTv.setText("My Page에 저장 되었습니다.");
				mCommentTv.setVisibility(View.VISIBLE);
			} else {
				mCommentTv.setText("");
				mCommentTv.setVisibility(View.GONE);
			}
			
			mNumLayout.setVisibility(View.VISIBLE);
			if(mLottoCount < 7) {
				setButtonClickable(true);
			} else if(mLottoCount == 7) {
				setSaveClickListener();
			}
		}
	}

	private void setButtonClickable(boolean clickable) {
		mNum1Btn.setClickable(clickable);
		mNum2Btn.setClickable(clickable);
		mNum3Btn.setClickable(clickable);
		mNum4Btn.setClickable(clickable);
		mNum5Btn.setClickable(clickable);
		mNum6Btn.setClickable(clickable);
		mAdImage.setClickable(clickable);
		mNumSaveBtn.setClickable(clickable);
	}

	@Override
	public void onBackPressed() {
		ApplicationUtils.showOkCancelDialog(mContext, 0,
				getString(R.string.popup_alert),
				getString(R.string.lotto_viewStop));
	}

	/*
	 * 로또 번호을 보여 주기 위해 로또 배경 이미지를 설정한다.
	 * @param	[IN] numBtn: 디스플레이할 버튼
	 * 			[IN] lottoNum: 디스플레이할 번호
	 * @return	-
	 */
	private void setBackGroundNum(Button numBtn, String lottoNum) {
		int num = Integer.parseInt(lottoNum);
		if (num > 0 && num < 11) {
			numBtn.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.lottoball_yellow));
		} else if (num < 21) {
			numBtn.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.lottoball_blue));
		} else if (num < 31) {
			numBtn.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.lottoball_red));
		} else if (num < 41) {
			numBtn.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.lottoball_black));
		} else {
			numBtn.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.lottoball_green));
		}
	}
	
	/*
	 * 이미지 다운로드를 완료함.
	 * @param	-
	 * @return 	-
	 */
	public void imageDownloaded() {
		CNCronosLog.d("이미지 다운로드 완료....");
		// 이미지 다운로드를 완료하였으므로 다음 이미지를 요청한다.
		mHandler.postDelayed(new nextImageRequestEnabledRunnable(),	100);
		
		if(mWorkingThread == false) {
			CNCronosLog.d("스레드가 시작중이지 않아 시작 요청함.");
			mWorkingThread = true;
			threadStart();
		} else {
			CNCronosLog.d("스레드가 시작중");
		}
	}
	
	private class nextImageRequestEnabledRunnable implements Runnable {

		@Override
		public void run() {
			
			boolean bNextImageDownloaded = false;
			do {
				if(mDownloadImageIndex < 7) {
					mDownloadImageIndex++;
					bNextImageDownloaded = mImageDownloader.download(mBgArr.get(mDownloadImageIndex), null, null);
				} else {
					break;
				}
			} while(bNextImageDownloaded == true);
		}
	}
	
	/*
	 * 이미지 출력이 완료된 후, 로또 번호를 보여 주기 위해 스레드를 시작시킨다.
	 * 
	 */
	public void threadStart(){
		mHandler.postDelayed(new setEnabledRunnable(), NUM_DELAY_TIME);
	}

	public void parsingLotto(Element xmlObject) throws Exception {

		String Tag = "parsingLotto";

		CNBaseDataParser parser = new CNLottoParser();
		CNResultSet resultSet = parser.parse(xmlObject);
		ArrayList<CNBaseDataSet> dataSet = null;

		mSendSeq = resultSet.getmSendSeq();

		if (resultSet != null) {
			dataSet = resultSet.getDataSetList();
			mNumArr.add(resultSet.getmLottoNum1());
			mNumArr.add(resultSet.getmLottoNum2());
			mNumArr.add(resultSet.getmLottoNum3());
			mNumArr.add(resultSet.getmLottoNum4());
			mNumArr.add(resultSet.getmLottoNum5());
			mNumArr.add(resultSet.getmLottoNum6());

			if (dataSet != null) {
				int count = dataSet.size();
				CNCronosLog.d(Tag, "DataSet.size():" + count);
				for (int i = 0; i < count; i++) {
					CNLottoAdLottoData data = (CNLottoAdLottoData) dataSet.get(i);

					CNCronosLog.d("============ " + i + " ============");

					CNCronosLog.d("mainUrl:" + data.adContents);

					mBgArr.add(data.adContents);
					CNCronosLog.d("mainUrl:" + mBgArr.get(i));

				}
			}

			if(mImageDownloader.download(mBgArr.get(mDownloadImageIndex), mAdImage, mProgressBar) == true) {
				imageDownloaded();
			}
		}
	}

	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");
		String url = null;
		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		switch (mCurrentIndex) {
			case INDEX_LOTTO_REQUEST:
				url = MnetGlobalApiSetEx.getLottoUrl(mContext, mSendSeq);
				break;
			case INDEX_LOTTO_SAVE:
				url = MnetGlobalApiSetEx.setLottoUrl(mContext, mSendSeq);
				break;
		}

		CNCronosLog.d("onGetAsyncRequestUrl", "url : " + url);

		return url;
	}

	@Override
	public void onAsyncCancelRequest() {
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage) {
		super.hideLoadingDialog();

		ApplicationUtils.showOkDialog(mContext, 0,
				getString(R.string.popup_alert), "기한이 지난 로또 입니다.",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						dialog.dismiss();
						finish();
					}
				});
	}

	@Override
	public void onAsyncPreRequest() {
		super.showLoadingDialog();
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject) {
		super.hideLoadingDialog();
		
		switch(mCurrentIndex){
		case INDEX_LOTTO_REQUEST:
			try {
				parsingLotto(xmlObject);
			} catch (Exception e) {
				
			}
			break;
		case INDEX_LOTTO_SAVE:
			Intent intent = new Intent(mContext,LottoAdTabActivity.class);
			intent.putExtra("currentTab", 3);
			startActivity(intent);
			finish();
			break;
		}
	}

	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();

		ApplicationUtils.showOkDialog(mContext, 0,
				getString(R.string.popup_alert),
				ApplicationUtils.getErrorMessage(mContext, errorNumber));
	}

	@Override
	protected void onDestroy() {
		recycleBitmap(mAdImage);
		super.onDestroy();
		mMediaPlayer.stop();
	}

	@Override
	protected void onResume() {
		super.onResume();

		onRequestData();

		if (!mMediaPlayer.isPlaying())
			mMediaPlayer.start();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mMediaPlayer.pause();
	}
	
	private void recycleBitmap(ImageView iv) {
		if(iv != null) {
			try {
				Drawable d = iv.getDrawable();
				if(d instanceof BitmapDrawable) {
					Bitmap b = ((BitmapDrawable)d).getBitmap();
					b.recycle();
				}
				
				d.setCallback(null);
			} catch(Exception e) {
				e.getStackTrace();
			}
		}
	}
}
